import Vue from 'vue'
import VueGridLayout from 'vue-grid-layout'

import pvtable from '@/components/gadget/pvtable/pvtable-gadget.vue'
import grid from '@/components/gadget/grid/grid-gadget.vue'
import checklistgadget from '@/components/gadget/check-list/checklist-gadget.vue'
import gridgadget from '@/components/gadget/grid-gadget/grid-gadget.vue'
import hierarchygridgadget from '@/components/gadget/hierarchy-grid/hierarchygrid-gadget.vue'
import crudformgadget from '@/components/gadget/crud-form/crudform-gadget.vue'
import chartgadget from '@/components/gadget/chart-line/line-gadget.vue'
import barchartgadget from '@/components/gadget/chart-bar/bar-gadget.vue'
import piechartgadget from '@/components/gadget/chart-pie/pie-gadget.vue'
import listmenu from '@/components/gadget/list-menu/list-menu-gadget.vue'
import dateRangeSlicer from '@/components/gadget/dateRange-slicer/daterange-gadget.vue'
import dateSlicer from '@/components/gadget/date-slicer/date-slicer-gadget.vue'
import runReport from '@/components/gadget/runreport-action/runreport-gadget.vue'
import kpigadget from '@/components/gadget/kpi/kpi-gadget.vue'
import circulargauge from '@/components/gadget/circular-gauge/circular-gadget.vue'
import cardicon from '@/components/gadget/card-icon/card-icon-gadget.vue'
import cardlinegadget from '@/components/gadget/card-line/card-line-gadget.vue'
import autorefreshgadget from '@/components/gadget/auto-refresh/auto-refresh-gadget.vue'
import dropdownlistgadget from '@/components/gadget/dropdown-list-slicer/dropdown-list-gadget.vue'
import treegridgadget from '@/components/gadget/tree-grid-gadget/tree-grid-gadget.vue'
import menulistgadget from '@/components/gadget/customized/menuList/menuList-gadget.vue'
import linkbuttongadget from '@/components/gadget/link-button/link-button-gadget.vue'
import checkboxgadget from '@/components/gadget/checkbox-slicer/checkbox-gadget.vue'
import multiselectgadget from '@/components/gadget/multi-select-slicer/multi-select-gadget'
import cardnumbergadget from '@/components/gadget/card-number/card-number-gadget.vue'
import htmleditorgadget from '@/components/gadget/html-editor/html-editor-gadget.vue'
// import treemapgadget from '@/components/gadget/tree-map/tree-map-gadget.vue'
import drilldowntreemapgadget from '@/components/gadget/drilldown-treemap/drilldown-treemap-gadget.vue'
import placeholdergadget from '@/components/gadget/place-holder/place-holder-gadget.vue'
import processgaugegadget from '@/components/gadget/gauge-stage/gauge-stage-gadget.vue'
import scorecardgadget from '@/components/gadget/score-card-gadget/score-card-gadget.vue'
import cardlablegadget from '@/components/gadget/card-lable/card-lable-gadget.vue'
import kanbangadget from '@/components/gadget/kanban/kanban-gadget'
import pageheadergadget from '@/components/gadget/page-header/page-header-gadget.vue'
import deptdefaultslicergadget from '@/components/gadget/customized/dept-default-slicer/dept-default-slicer-gadget.vue'
import nextticketviewgadget from '@/components/gadget/next-ticket-view/next-ticket-view-gadget'
import {
  getUUID
} from '@/utils'
// Customized
import bottriggerreportgadget from '@/components/gadget/customized/bot-trigger/bot-trigger-gadget.vue'
import bottriggerpvtablegadget from '@/components/gadget/customized/bot-trigger/bot-trigger-pvtble-gadget.vue'
import bottriggeruserreportgadget from '@/components/gadget/customized/bot-trigger-user/bot-trigger-user-gadget.vue'
import crudgadget from '@/components/gadget/crud-gadget/crud-gadget.vue'
import stepgadget from '@/components/gadget/step-line/step-line-gadget.vue'
import newstepgadget from '@/components/gadget/new-step-line/new-step-line-gadget.vue'
import homepagegadget from '@/components/gadget/home-page/home-page-gadget.vue'
import customizedmultiselectgadget from '@/components/gadget/customized/multi-select-slicer/multi-select-gadget'
import customizeduserdropdownlistgadget from '@/components/gadget/customized/user-dropdown-list-slicer/user-dropdown-list-gadget.vue'
import customizedusermultipledropdownlistgadget from '@/components/gadget/customized/user-multiple-dropdown-list-slicer/user-multiple-dropdown-list-gadget.vue'
import appstabsgadget from '@/components/gadget/apps-tabs/apps-tabs-gadget.vue'
import usertimezoneinfocardgadget from '@/components/gadget/customized/user-timezone-info-card/user-timezone-info-card-gadget.vue'
import attendancegadget from '@/components/gadget/customized/attendance-gadget/attendance-gadget.vue'
import recordgadget from '@/components/gadget/customized/record-gadget/record-gadget.vue'
import usergadget from '@/components/gadget/customized/user-gadget/user-gadget.vue'
import botsgadget from '@/components/gadget/customized/bots-gadget/bots-gadget.vue'
import workschedulegadget from '@/components/gadget/customized/workschedule-gadget/workschedule-gadget.vue'
import enterinputgadget from '@/components/gadget/enter-input-slicer/enter-input-gadget.vue'
import apigridgadget from '@/components/gadget/api-grid-gadget/api-grid-gadget.vue'
import crudformplusgadget from '@/components/gadget/crud-form-plus/crudform-plus-gadget.vue'
import heatmapgadget from '@/components/gadget/chart-heatmap/heatmap-gadget'
// dashboardGadgetList
import {
  dashboardGadgetList
} from '@/utils/data-json'

export default {
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    grid,
    checklistgadget,
    gridgadget,
    hierarchygridgadget,
    crudformgadget,
    htmleditorgadget,
    pvtable,
    chartgadget,
    barchartgadget,
    piechartgadget,
    heatmapgadget,
    listmenu,
    dateRangeSlicer,
    runReport,
    kpigadget,
    circulargauge,
    cardicon,
    cardlinegadget,
    dateSlicer,
    autorefreshgadget,
    dropdownlistgadget,
    treegridgadget,
    menulistgadget,
    linkbuttongadget,
    checkboxgadget,
    multiselectgadget,
    cardnumbergadget,
    // treemapgadget,
    drilldowntreemapgadget,
    placeholdergadget,
    processgaugegadget,
    scorecardgadget,
    cardlablegadget,
    kanbangadget,
    pageheadergadget,
    // pageheadergadgetnexticket,
    // Customized
    bottriggerreportgadget,
    bottriggerpvtablegadget,
    bottriggeruserreportgadget,
    crudgadget,
    stepgadget,
    newstepgadget,
    homepagegadget,
    customizedmultiselectgadget,
    customizeduserdropdownlistgadget,
    customizedusermultipledropdownlistgadget,
    deptdefaultslicergadget,
    nextticketviewgadget,
    appstabsgadget,
    usertimezoneinfocardgadget,
    attendancegadget,
    recordgadget,
    usergadget,
    botsgadget,
    workschedulegadget,
    apigridgadget,
    enterinputgadget,
    crudformplusgadget
  },
  provide () {
    return {
      gadgetMessageBus: this.gadgetMessageBus,
      slicer: this.slicer,
      filters: this.filters,
      gadgetInfos: () => this.gadgetInfos
    }
  },
  data () {
    return {
      pageId: this.$getQuery('pageid'),
      gadgetMessageBus: new Vue(),
      slicer: {},
      filters: [],
      gadgetInfos: [],
      showCloseIcon: true,
      contenttemplateVue: '',
      editMode: false,
      editText: 'Edit',
      dashbordDefaultSetting: {
        allowResizing: false,
        allowDragging: false,
        responsive: true
      },
      gadgets: [],
      dialog: false,
      selectedgadget: '',
      loading: false,
      layoutLists: dashboardGadgetList,
      userGadgetList: [],
      showMsg: false,
      businessTypeForWidget: '',
      reportNameForPage: '',
      reportIntegrationCode: [],
      dashboardId: null
    }
  },

  computed: {
    publishedLayoutItems () {
      return this.layoutLists.filter(item => item.group === 'published')
    },
    inDevLayoutItems () {
      return this.layoutLists.filter(item => item.group === 'inDev')
    },
    customizedLayoutItems () {
      return this.layoutLists.filter(item => item.group === 'customized')
    }
  },
  created () {
    this.getQureAll()
    this.getDashboardLayout()
    this.getReportItemInfo()
    this.gadgetMessageBus.$on(this.pageId + 'mouseevent', (e) => {
      this.moveComponent(e)
    })
    this.gadgetMessageBus.$on(this.pageId + 'addgauge', (e) => {
      this.addgauge()
    })
    this.gadgetMessageBus.$on(this.pageId + 'toggleClick', (e) => {
      this.toggleClick()
    })
    this.gadgetMessageBus.$on(this.pageId + 'showEditMode', (e) => {
      this.showEditMode()
    })
    this.gadgetMessageBus.$on(this.pageId + 'hideEditMode', (e) => {
      this.hideEditMode()
    })
  },
  beforeDestroy () {
    this.gadgetMessageBus.$off()
  },
  methods: {
    addgauge () {
      this.editMode = true
      this.dashbordDefaultSetting.allowResizing = true
      this.editText = 'Save'
      this.selectedgadgetPop()
      this.gadgetMessageBus.$emit(this.pageId + 'showDesign')
    },
    showEditMode () {
      this.editMode = true
      this.dashbordDefaultSetting.allowResizing = true
    },
    hideEditMode () {
      this.editMode = false
      this.dashbordDefaultSetting.allowResizing = false
    },
    getDashboardLayout () {
      var _self = this
      this.loading = true
      this.gadgetInfos = []
      if (this.pageId === '') {
        return
      }
      const params = {
        businessId: this.pageId
      }
      var sourceTenantCode = sessionStorage.getItem('isMySelfCode') ? sessionStorage.getItem('isMySelfCode') : this.$store.state.user.tenantCode
      this.$interface.reports.getDashboardLayout(params, sourceTenantCode)
        .then(({
          data: res
        }) => {
          this.loading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            _self.reportNameForPage = res.data.name
            _self.businessTypeForWidget = res.data.businessType
            _self.reportIntegrationCode = res.data.integrationCode ? res.data.integrationCode : []
            _self.gadgets = ((res.data.contentNew && res.data.contentNew.length) > 0 ? res.data.contentNew : JSON.parse(res.data.content)) || []
            _self.dashboardId = res.data.id
            this._.forEach(_self.gadgets, function (value, key) {
              _self.gadgetInfos.push({
                id: value.i,
                gadgetStatus: 'init',
                gadgetType: value.com ? value.com : ''
              })
            })
            for (let index = 0; index < _self.gadgets.length; index++) {
              const element = _self.gadgets[index]
              if (element.static) {
                delete element.static
              }
              if (element.com === 'pageheadergadget' || element.com === 'pageheadergadgetnexticket') {
                element.h = 3
                element.static = true
              }
            }
            _self.$store.commit('SET_GADGET_LAYOUT', _self.gadgets)
          }
          if (!res.data.permission && res.data.permission !== undefined) {
            this.$router.replace({ name: '404' })
          }
        })
    },

    gadgetDragChanged (e) {
      this.dashbordDefaultSetting.allowDragging = e.state
    },
    gadgetRemoved (e) {
      var index = this.getGadgetIndex(e.id)
      this.gadgets.splice(index, 1)
      this.onSave()
      this.gadgetMessageBus.$emit(this.pageId + 'gadgetremoved', e.id)
    },
    getGadgetIndex (id) {
      for (var i = 0; i < this.gadgets.length; i++) {
        if (this.gadgets[i].i === id) {
          return i
        }
      }
    },
    onSave () {
      let dashboardlayout = JSON.stringify(this.gadgets)
      if (dashboardlayout) {
        const params = {
          tenantCode: this.$store.state.user.tenantCode,
          type: 1,
          businessId: this.pageId,
          content: dashboardlayout,
          contentNew: this.gadgets,
          id: this.dashboardId
        }
        this.$interface.reports.saveDashboardLayout(params).then(({
          data: res
        }) => {
          this.gadgetMessageBus.$emit(this.pageId + 'closeLoading')
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.showMsg = false
            this.$store.state.contentIsNeedRefresh = true
            this.$nextTick(() => {
              this.$store.state.contentIsNeedRefresh = false
            })
            return this.$message.success(this.$t('custom.dashboard.layoutSavedMessage') + res.msg)
          }
        })
      }
    },
    toggleClick () {
      this.editMode = !this.editMode
      if (this.editMode) {
        this.dashbordDefaultSetting.allowResizing = true
        this.editText = 'Save'
      } else {
        this.onSave()
        this.dashbordDefaultSetting.allowResizing = false
        this.editText = 'Edit'
      }
    },
    selectedgadgetPop () {
      this.dialog = true
    },
    addWidget (item, type = 'add', gadgetId = null) {
      this.dialog = false
      let getI = type === 'update' ? gadgetId : getUUID()
      let newWidget = {
        'x': item.x || 0,
        'y': item.y || 0,
        'w': item.w || 6,
        'h': item.h || 16,
        'i': getI,
        com: item.key
      }
      this.gadgets.push(newWidget)
    },
    resizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      this.gadgets[index].h = newH
      this.gadgets[index].w = newW

      let refsList = this.$refs.gadgets || []
      for (let ind = 0; ind < refsList.length; ind++) {
        const elementId = refsList[ind].id
        if (elementId === i && index > -1) {
          this.$refs.gadgets[ind].resized(i, newH, newW, newHPx, newWPx)
        }
      }
    },
    containerResizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      this.gadgets[index].h = newH
      this.gadgets[index].w = newW
      let refsList = this.$refs.gadgets || []
      for (let ind = 0; ind < refsList.length; ind++) {
        const elementId = refsList[ind].id
        if (elementId === i && index > -1) {
          this.$refs.gadgets[ind].containerResizedEvent(i, newH, newW, newHPx, newWPx)
        }
      }
    },
    mouseEnterModule (index) {
      if (this.editMode) {
        this.$set(this.gadgets[index], 'showSetting', 'show')
      }
    },
    mouseLeaveModule (index) {
      if (this.editMode) {
        this.$delete(this.gadgets[index], 'showSetting')
      }
    },
    moveComponent (status) {
      if (this.editMode) {
        this.gadgetDragChanged({
          state: status
        })
      }
    },
    editComponent (componentId) {
      try {
        let index = this.getGadgetIndex(componentId)
        let refsList = this.$refs.gadgets || []

        for (let i = 0; i < refsList.length; i++) {
          const elementId = refsList[i].id
          if (elementId === componentId && index > -1) {
            this.$refs.gadgets[i].showQueryModel()
          }
        }
      } catch (error) {}
    },
    closeComponent (componentId) {
      let confirmText = [
        'Are you sure to remove widget from dashboard layout?',
        'Click confirm will continue remove widget and save layout'
      ]
      const newDatas = []
      const h = this.$createElement
      for (const i in confirmText) {
        newDatas.push(h('p', null, confirmText[i]))
      }
      this.$confirm('info', {
        title: this.$t('prompt.title'),
        message: h('div', null, newDatas),
        showCancelButton: true,
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(async () => {
        this.gadgetRemoved({
          id: componentId
        })
      }).catch(_ => {})
    },
    getQureAll () {
      try {
        let hasQure = decodeURIComponent(window.location.search).split('?').length > 1
        hasQure && decodeURIComponent(window.location.search).split('?')[1].split('&').map(e => {
          this.$set(this.slicer, e.split('=')[0], e.split('=')[1])
        })
      } catch (error) {}
    },
    addGadgetToPage (row) {
      if (this.gadgets.findIndex(e => e.i === row.gadgetId) > -1) {
        return this.$message.error(this.$t('custom.report.disabledAddSaveGadget'))
      }
      let itemWidget = this.layoutLists.find(e => e.key === row.gadgetType)
      this.addWidget(itemWidget, 'update', row.gadgetId)
    },
    deleteGadgetToPage (row) {
      const params = {
        ...row,
        reuse: false
      }
      this.$interface.reports.postReportSetting(params).then(({
        data: res
      }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.showSettingInternal = false
        this.$emit('queryModelClosed', this.showSettingInternal)
        return this.$message.success(res.msg)
      }).catch(() => {})
    }

  }
}
